package yl.hs.bmipfull.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import yl.hs.bmipfull.security.TokenUtils;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public WebResult customException(HttpServletRequest request, Exception e, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", request.getRequestURL().toString());
        map.put("exception", e.getMessage());
        log.error(request.getRequestURL().toString(),e);
        return new WebResult(ResultCode.ERROR, "error", map);
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public WebResult customException(HttpServletRequest request, RuntimeException e, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", request.getRequestURL().toString());
        map.put("exception", e.getMessage());
        log.error(request.getRequestURL().toString(),e);
        return new WebResult(ResultCode.ERROR, "error", map);
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public WebResult customException(HttpServletRequest request, AccessDeniedException e, HttpServletResponse response) {
        var authentication = TokenUtils.getAuthenticationFromToken(request);
        return new WebResult(ResultCode.UNAUTHOR.code);
    }
}
